package com.hankol.newretail.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import cn.iwgang.countdownview.CountdownView
import com.baselibrary.extension.buildSpannableString
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.toast
import com.baselibrary.utils.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.hankol.newretail.R
import com.hankol.newretail.adapter.CancelOrderReasonAdapter
import com.hankol.newretail.adapter.GoodsListingAdapter
import com.hankol.newretail.adapter.SeeReasonGoodsListingAdapter
import com.hankol.newretail.adapter.details.GoodsCoverPopVpAdapter
import com.hankol.newretail.bean.*
import com.hankol.newretail.bean.goods_details.GoodsGiftBean
import com.hankol.newretail.bean.goods_details.MallProductGiftCommodityVo
import com.hankol.newretail.fragment.GoodsPlantFragment
import com.hankol.newretail.widget.GoodsVideoView
import kotlin.math.roundToInt

/**新零售相关弹窗
 * @author: merbng
 * @time: 2022/8/10 14:46
 * @description:
 */
object RetailPopUtils {
    interface ICallback4Ok {
        fun onClickOk()
        fun onClickWait()
    }

    interface ICallback4UseCoin {
        fun onClickConfirm(isUse: Boolean)
    }

    /**使用酒币弹窗
     * @author: merbng
     * @time: 2022/8/6 15:08
     * @description:
     * useScoreStatus:使用酒币：0使用，1不使用  回显
     */
    @JvmStatic
    fun showUseWineCoin(act: Activity, scoreInfo: ScoreInfoBean, useScoreStatus: Int, callback: ICallback4UseCoin) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_use_winery_coin, null)
        view.findViewById<TextView>(R.id.tv_coin_num).setText("酒币（共${scoreInfo.myScore}个）")
        view.findViewById<TextView>(R.id.tv_use_price).buildSpannableString {
            addText("使用${scoreInfo.consumeScore}酒币 抵扣  ") {
                setColor("#333333")
            }
            addText("¥${AmountUtil.changeF2YKeepTwo("${scoreInfo.scoreDeductPrice}")}") {
                setColor("#F54D53")
            }
        }
        view.findViewById<TextView>(R.id.tv_tip).setText("订单最高可使用${scoreInfo.consumeScore}酒币，抵扣 ¥${AmountUtil.changeF2YKeepTwo("${scoreInfo.scoreDeductPrice}")}")
        val cbUse = view.findViewById<CheckBox>(R.id.cb_use)
        cbUse.isChecked = useScoreStatus == 0
        val cbNoUse = view.findViewById<CheckBox>(R.id.cb_no)
        cbNoUse.isChecked = useScoreStatus == 1
        view.findViewById<LinearLayout>(R.id.ll_use).setOnClickListener {
            cbUse.isChecked = true
            cbNoUse.isChecked = false
        }
        view.findViewById<LinearLayout>(R.id.ll_no_use).setOnClickListener {
            cbUse.isChecked = false
            cbNoUse.isChecked = true
        }
        view.findViewById<ImageView>(R.id.iv_close).setOnClickListener { dialog.dismiss() }
        view.findViewById<ImageView>(R.id.iv_close_ruler).setOnClickListener {
            view.findViewById<LinearLayout>(R.id.ll_coin_ruler).visibility = View.GONE
            view.findViewById<LinearLayout>(R.id.ll_coin).visibility = View.VISIBLE
        }
        view.findViewById<TextView>(R.id.tv_ok_ruler).setOnClickListener {
            view.findViewById<LinearLayout>(R.id.ll_coin_ruler).visibility = View.GONE
            view.findViewById<LinearLayout>(R.id.ll_coin).visibility = View.VISIBLE
        }
        view.findViewById<TextView>(R.id.tv_use_rules).setOnClickListener {
            val webview = window.findViewById<BridgeWebView>(R.id.webView)
            webview.webViewClient = MyWebViewClient(webview)
            val dictionary = SpUtils.getInstance().loadDictionaryrBean
            val desc = dictionary.getByName_system("currencyRules")
            webview.loadData(desc, "text/html; charset=UTF-8", "UTF-8")
            view.findViewById<LinearLayout>(R.id.ll_coin_ruler).visibility = View.VISIBLE
            view.findViewById<LinearLayout>(R.id.ll_coin).visibility = View.GONE
        }
        view.findViewById<TextView>(R.id.tv_ok).setOnClickListener {
            callback.onClickConfirm(cbUse.isChecked)
            dialog.dismiss()
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }

    /**商品清单 弹窗
     * @author: merbng
     * @time: 2022/8/6 15:08
     * @description:
     */
    @JvmStatic
    fun showGoodListingDialog(act: Activity, goodsListData: List<MallOrderSkuDtoBean>) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = ScreenUtils.getScreenHeight() / 3 * 2
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_goods_listing, null)
        view.findViewById<ImageView>(R.id.iv_close).setOnClickListener { dialog.dismiss() }
        val rvGoods = view.findViewById<RecyclerView>(R.id.rv_goods)
        val mAdapter = GoodsListingAdapter()
        rvGoods.adapter = mAdapter
        mAdapter.setNewData(goodsListData)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val dictionary = SpUtils.getInstance().loadDictionaryrBean
            val desc = dictionary.getByName_system("currencyRules")
            RetailPopUtils.goodsServerPop(act, null, desc, "酒币规则")
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }

    /**支付剩余时间 07:16 弹窗
     * @author: merbng
     * @time: 2022/8/6 15:08
     * @description:
     */
    @JvmStatic
    fun showPayBackDialog(act: Activity, overtime: Long, callback: ICallback4Ok): CountdownView? {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.dialog_pay_back, null)
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            callback.onClickOk()
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.tv_ok).setOnClickListener {
            callback.onClickWait()
            dialog.dismiss()
        }
        val countdown = view.findViewById<CountdownView>(R.id.countdownView)

        //countdown.start(overtime.minus(TimeUtil.getCurrentTimeMillis()))
        window.setContentView(view)
        window.setGravity(Gravity.CENTER)
        return countdown
    }

    interface ICallBack4CancelOrderSelectReson {
        fun onClickOk(isRebackCart: Boolean, cancellationId: Int)
    }

    interface ICallBack4BackMoneyReson {
        fun onClickOk(bean: CancelReasonListBean)
    }

    /**取消订单 弹窗
     * @author: merbng
     * @time: 2022/8/10 15:27
     * @description:
     */
    @JvmStatic
    fun showCancelOrderDialog(act: Activity, reasonList: List<CancelReasonListBean>, callback: ICallBack4CancelOrderSelectReson) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_cancel_order, null)
        view.findViewById<ImageView>(R.id.iv_close).setOnClickListener { dialog.dismiss() }
        val imgSwitch = view.findViewById<ImageView>(R.id.img_switch)
        imgSwitch.isSelected = true
        view.findViewById<ImageView>(R.id.img_switch).setOnClickListener {
            imgSwitch.isSelected = !imgSwitch.isSelected
        }
        val rvList = view.findViewById<RecyclerView>(R.id.rv_goods)
        val mAdapter = CancelOrderReasonAdapter()
        rvList.adapter = mAdapter

        var tvOk = view.findViewById<TextView>(R.id.tv_ok)
        mAdapter.setNewData(reasonList)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            for (reasonListBean in mAdapter.data) {
                reasonListBean.isSelect = false
            }
            mAdapter.data[position].isSelect = true
            tvOk.setBackgroundResource(R.drawable.shape_rc_23_solid_f54d53)
            tvOk.isEnabled = true
            mAdapter.notifyDataSetChanged()
        }
        tvOk.setOnClickListener {
            var cancellationId = 0
            for (bean in mAdapter.data) {
                if (bean.isSelect) {
                    cancellationId = bean.cancellationId
                }
            }
            if (cancellationId == 0) {
                "请选择".toast()
                return@setOnClickListener
            }
            callback.onClickOk(imgSwitch.isSelected, cancellationId)
            dialog.dismiss()
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }

    /**
     * 商品详情，服务弹窗 酒币规则复用
     */
    fun goodsServerPop(act: Activity, adapter: BaseQuickAdapter<MallLabelBean, BaseViewHolder>?, des: String?, title: String = "服务描述"): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = (ScreenUtils.getScreenHeight() / 1.7f).roundToInt()
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.dialog_goods_details_service_des)
        window.setGravity(Gravity.BOTTOM)
        val ivGoodsServiceClose = window.findViewById<ImageView>(R.id.iv_goods_service_close)
        val rvGoodsServiceList = window.findViewById<RecyclerView>(R.id.rv_goods_service_list)
        val webview = window.findViewById<BridgeWebView>(R.id.webView)
        val tvGoodsAffirm = window.findViewById<TextView>(R.id.tv_goods_affirm)
        window.findViewById<TextView>(R.id.tv_goods_service_title).setText(title)
        rvGoodsServiceList.layoutManager = LinearLayoutManager(act)
        ivGoodsServiceClose.setOnClickListener { dialog.dismiss() }
        tvGoodsAffirm.setOnClickListener { dialog.dismiss() }
        if (adapter != null) {
            rvGoodsServiceList.visibility = View.VISIBLE
            rvGoodsServiceList.adapter = adapter
        } else {
            rvGoodsServiceList.visibility = View.GONE
        }
        if (des.isNullOrEmpty()) {
            webview.visibility = View.GONE
        } else {
            webview.visibility = View.VISIBLE
            webview.webViewClient = MyWebViewClient(webview)
            webview.loadData(des, "text/html; charset=UTF-8", "UTF-8")
        }
        return dialog
    }

    /**
     * 赠品优惠弹窗
     */
    fun goodsGiftPop(act: Activity, adapter: BaseQuickAdapter<MallProductGiftCommodityVo, BaseViewHolder>?, giftData: GoodsGiftBean?): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = (ScreenUtils.getScreenHeight() / 1.7f).roundToInt()
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.dialog_goods_details_gift)
        window.setGravity(Gravity.BOTTOM)
        window.findViewById<TextView>(R.id.tv_gift_condition).text = "每购买${giftData?.buyNum}件，赠送下列商品，赠完为止"
        val ivGoodsServiceClose = window.findViewById<ImageView>(R.id.iv_goods_service_close)
        val rvGiftList = window.findViewById<RecyclerView>(R.id.rv_gift_list)
        val tvGoodsAffirm = window.findViewById<TextView>(R.id.tv_goods_affirm)
        rvGiftList.layoutManager = LinearLayoutManager(act)
        ivGoodsServiceClose.setOnClickListener { dialog.dismiss() }
        tvGoodsAffirm.setOnClickListener { dialog.dismiss() }
        if (adapter != null) {
            rvGiftList.visibility = View.VISIBLE
            rvGiftList.adapter = adapter
        } else {
            rvGiftList.visibility = View.GONE
        }
        return dialog
    }


    /**
     * 商品详情，种草秀
     */
    fun goodsPlantPop(act: Activity, goodsId: Long, manager: FragmentManager): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = (ScreenUtils.getScreenHeight() / 1.7f).roundToInt()
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val newInstance = GoodsPlantFragment.newInstance(goodsId)
        manager.beginTransaction().add(R.id.fl_plant_info, newInstance).commit()
        window.setContentView(R.layout.dialog_goods_plant_lnfo)


/*

        var findViewById = window.findViewById<FrameLayout>(R.id.fl_plant_info)

        val fragment: GoodsPlantFragment = GoodsPlantFragment.newInstance(goodsId)
        val transaction = manager.beginTransaction()
        transaction.add(R.id.fl_plant_info, fragment).commit()
*/

        window.setGravity(Gravity.BOTTOM)
        window.findViewById<ImageView>(R.id.iv_goods_service_close).setOnClickListener { dialog.dismiss() }
        return dialog
    }


    /**
     * 商品详情，封面弹窗
     */
    @SuppressLint("SetTextI18n")
    fun goodsCoverPop(act: Activity, vpAdapter: GoodsCoverPopVpAdapter, pos: Int, listener: GoodsCoverPopVpAdapter.OnItemClickListener): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.dialog_goods_details_cover)
        window.setGravity(Gravity.CENTER)
        val vpGoodsCover = window.findViewById<ViewPager>(R.id.vp_goods_cover)
        val ivGoodsCoverClose = window.findViewById<ImageView>(R.id.iv_goods_cover_close)
        val tvGoodsCoverIndex = window.findViewById<TextView>(R.id.tv_goods_cover_index)
        vpGoodsCover.offscreenPageLimit = vpAdapter.list.size

        vpGoodsCover.adapter = vpAdapter
        if (pos < vpAdapter.count) {
            vpGoodsCover.setCurrentItem(pos, true)
            tvGoodsCoverIndex.text = "${pos + 1}/${vpAdapter.count}"
            if (pos == 0) {
                tvGoodsCoverIndex.visibility = View.GONE
            } else {
                tvGoodsCoverIndex.visibility = View.VISIBLE
            }
        }
        vpGoodsCover.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            @SuppressLint("SetTextI18n")
            override fun onPageSelected(position: Int) {
                if (position > 0) {
                    vpAdapter.goodsVideoView.stopPlay()
                }
                tvGoodsCoverIndex.text = "${position + 1}/${vpAdapter.count}"
                if (position == 0) {
                    tvGoodsCoverIndex.visibility = View.GONE
                } else {
                    tvGoodsCoverIndex.visibility = View.VISIBLE
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

        dialog.setOnDismissListener {
            listener.onItemClick(vpAdapter.mGsvGoodsMedialVideo)
        }

        vpAdapter.setOnItemClickListener(object : GoodsCoverPopVpAdapter.OnItemClickListener {
            override fun onItemClick(gsvGoodsMedialVideo: GoodsVideoView?) {
                dialog.dismiss()
                listener.onItemClick(vpAdapter.mGsvGoodsMedialVideo)
            }

        })

        ivGoodsCoverClose.setOnClickListener {
            dialog.dismiss()
            listener.onItemClick(vpAdapter.mGsvGoodsMedialVideo)
        }

        return dialog
    }


    /**退款原因 弹窗
     * @author: merbng
     * @time: 2022/8/10 15:27
     * @description:
     */
    @JvmStatic
    fun showRefundedReasonDialog(act: Activity, reasonList: List<CancelReasonListBean>, callback: ICallBack4BackMoneyReson) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_refunded_reason, null)
        view.findViewById<ImageView>(R.id.iv_close).setOnClickListener { dialog.dismiss() }
        val rvList = view.findViewById<RecyclerView>(R.id.rv_goods)
        val mAdapter = CancelOrderReasonAdapter()
        rvList.adapter = mAdapter

        var tvOk = view.findViewById<TextView>(R.id.tv_ok)
        mAdapter.setNewData(reasonList)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            for (reasonListBean in mAdapter.data) {
                reasonListBean.isSelect = false
            }
            mAdapter.data[position].isSelect = true
            tvOk.setBackgroundResource(R.drawable.shape_rc_23_solid_f54d53)
            tvOk.isEnabled = true
            mAdapter.notifyDataSetChanged()
        }
        tvOk.setOnClickListener {
            var cancellationId = 0
            var mBean: CancelReasonListBean? = null
            for (bean in mAdapter.data) {
                if (bean.isSelect) {
                    cancellationId = bean.cancellationId
                    mBean = bean
                }
            }
            if (cancellationId == 0) {
                "请选择".toast()
                return@setOnClickListener
            }
            if (mBean.checkNotNull()) {
                mBean?.let {
                    callback.onClickOk(mBean)
                }
            }
            dialog.dismiss()
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }

    /**查看原因 弹窗
     * @author: merbng
     * @time: 2022/8/6 15:08
     * @description:
     */
    @JvmStatic
    fun showSeeReasonDialog(act: Activity, goodsListData: List<NoSupportSkuDtoBean>) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = ScreenUtils.getScreenHeight() / 3 * 2
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_see_reason, null)
        view.findViewById<ImageView>(R.id.iv_close).setOnClickListener { dialog.dismiss() }
        val rvGoods = view.findViewById<RecyclerView>(R.id.rv_goods)
        val mAdapter = SeeReasonGoodsListingAdapter()
        rvGoods.adapter = mAdapter
        mAdapter.setNewData(goodsListData)
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }
}